package com.kun.alldb.support.dbmanager.rdbms;

import com.kun.alldb.base.DatasourceBase;
import com.kun.alldb.support.DBManager;
import com.kun.alldb.support.adaptor.DataSourceAdaptor;
import com.kun.alldb.wrapper.ConstantWrapper;
import com.kun.db.Db;
import com.kun.db.DbUtil;
import com.kun.db.Entity;
import com.kun.db.meta.MetaUtil;
import lombok.extern.slf4j.Slf4j;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author kun.li
 */
@Slf4j
public class DefaultDBManager extends DBManager {

    /**
     * 数据源操作对象
     */
    protected Db db;

    public DefaultDBManager(DatasourceBase datasourceBase) {
        super(datasourceBase);
        DataSource dataSource = DataSourceAdaptor.getDataSource(datasourceBase);
        db = DbUtil.use(dataSource);
        char wrapQuote = MetaUtil.getIdentifierQuote(dataSource).charAt(0);
        constantWrapper = new ConstantWrapper(wrapQuote);
    }


    @Override
    public boolean checkDataSource() {
        try (Connection connection = db.getConnection()) {
            return true;
        } catch (SQLException sqlException) {
            log.error("连接校验失败", sqlException);
            return false;
        }
    }

    @Override
    public long count(Entity entity) {
        try {
            return db.count(entity);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }


}
